//
//  DDQuestionFollowAnswerViewController.m
//  dingdang
//
//  Created by Chen Jing on 15/7/31.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDQuestionFollowAnswerViewController.h"
#import "PlaceholderTextView.h"
#import "UIImageView+WebCache.h"
#import "DDNetWorkAPIClient.h"
#import "PECropViewController.h"
#import "JSONKit.h"

#import "DDMediaVC.h"
#import "DDQuestionView.h"

@interface DDQuestionFollowAnswerViewController ()<PECropViewControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    DDNetWorkAPIClient * client;
    NSString * param_content;
    NSMutableArray * param_dataArray;
    UIImage * paramImage_process;
    CGSize hold_scrollView_contentSize;
    CGSize temp_scrollView_contentSize;
}
@property (weak, nonatomic) IBOutlet UIImageView *imageView_head;
@property (weak, nonatomic) IBOutlet UILabel *label_userName;
@property (weak, nonatomic) IBOutlet UILabel *label_date;
@property (weak, nonatomic) IBOutlet UILabel *label_body;
@property (weak, nonatomic) IBOutlet PlaceholderTextView *textView_reply;
@property (weak, nonatomic) IBOutlet UIButton *btn_record;
@property (weak, nonatomic) IBOutlet UIButton *btn_camara;
@property (weak, nonatomic) IBOutlet UIButton *btn_photo;
@property (weak, nonatomic) IBOutlet UIView *contentOfImageView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *contentOfMain;
@property (weak, nonatomic) IBOutlet UIView *contentOfBottom;

@end

@implementation DDQuestionFollowAnswerViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createUI];
    [self createData];
}

-(void)viewWillAppear:(BOOL)animated{
    CGFloat width = CGRectGetWidth([[UIScreen mainScreen]bounds]);
    self.btn_record.center = CGPointMake(width / 4.0, 53);
    self.btn_camara.center = CGPointMake((width / 4.0) * 2, 53);
    self.btn_photo.center = CGPointMake((width / 4.0) * 3, 53);
    hold_scrollView_contentSize = CGSizeMake(self.view.frame.size.width, self.contentOfMain.frame.size.height - self.contentOfBottom.frame.size.height);
    self.scrollView.contentSize = hold_scrollView_contentSize;
}

-(void)createUI{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;

    //自定义TAB BAR UI
    [self addNavigatorTitle:@"追问" parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];

    [self AddLeftBtnAction:@"" normal:@"top_返回" selected:@"top_返回" action:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];

    __weak DDQuestionFollowAnswerViewController * weakSelf = self;
    [self AddRightBtnAction:@"提交" normal:@"" selected:@"" action:^{
        [weakSelf commit];

    }];

    self.imageView_head.layer.cornerRadius = 25;
    self.imageView_head.layer.masksToBounds = YES;
    [self.imageView_head sd_setImageWithURL:[NSURL URLWithString:self.info_element.userAvatarUrl] placeholderImage:[UIImage imageNamed:@"个人中心-人数统计头像"]];
    self.label_userName.text = self.info_element.userName;
    self.label_date.text = self.info_element.answerTime;
    for (DDQuestionAnswerExplanation * explan in self.info_element.explanation) {
        if ([explan.type isEqualToString:@"TEXT"]) {
            self.label_body.text = explan.text;
        }
    }

    self.textView_reply.layer.cornerRadius = 10;
    self.textView_reply.layer.masksToBounds = YES;
    self.textView_reply.placeholder = @"请输入内容";
    self.textView_reply.layer.borderWidth = .5;
    self.textView_reply.layer.borderColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1].CGColor;

    //增加一个控制器，用来做多媒体那块
    DDMediaVC *vc = [[DDMediaVC alloc] initWithNibName:@"DDMediaVC" bundle:nil];//[DDMediaView loadFromNib];
    [self addChildViewController:vc];
    UIView * mediaView = vc.view;
    mediaView.frame = CGRectMake(0, self.view.frame.size.height - 88, self.view.frame.size.width, mediaView.frame.size.height);
    vc.mediaForPhoto = ^(UIImage *image,NSString *url)
    {

        NSDictionary * tempDic = @{
                                   @"type": @"IMAGE",
                                  // @"url": url,
                                   @"url" : image
                                   };
        [param_dataArray addObject:tempDic];

        [self resetImageAndRecordViews];


//        DDQuestionView *qview = self.view.scrollView.subviews[_currentPage];
//        [qview reloadDataForAnswers:image url:url];
    };
    vc.mediaForAudio = ^(NSString *path,NSString *time,NSString *url)
    {

        NSDictionary * tempDic = @{
                                   @"type": @"VOICE",
                                   @"url": url,
                                   };
        [param_dataArray addObject:tempDic];

        [self resetImageAndRecordViews];
//        DDQuestionView *qview = self.view.scrollView.subviews[_currentPage];
//        [qview reloadDataForAnswers:path time:time url:url];
    };
    [self.view addSubview:mediaView];
}

-(void)commit{
    [self showHUD:@""];
    BOOL isSuccess = [self assembleDic];
    if (isSuccess == NO) {
        [self hideHUD];
        return;
    }
    if (param_content == nil) {
        param_content = @"";
    }

    NSDictionary * tempDic = nil;
    if (self.info_parent != 0) {
        tempDic = @{
                    @"answerId" : self.info_element.id,
                    @"content" : param_content,
                    @"parent" : @"",
                    };
    }else{
        tempDic = @{
                    @"answerId" : self.info_element.id,
                    @"content" : param_content,
                    };
    }

    [client mainQuestionReply:tempDic completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        if ([object[@"message"] isEqualToString:@"成功"]) {
            [self.navigationController popViewControllerAnimated:YES];
        }
        [self hideHUD];
    }];
}

-(void)createData{
    param_dataArray = [NSMutableArray array];
    client = [[DDNetWorkAPIClient alloc]init];
}

-(BOOL)assembleDic{
    BOOL isSuccess = NO;
    /*
     [
        {
             "id": 17,
             "type": "TEXT",
             "title": null,
             "text": "这是测试的题目",
             "url": null,
             "description": null,
             "labels": null
        }
     ]
     */
    if (param_dataArray.count > 0 || self.textView_reply.text.length > 0) {
        isSuccess = YES;
    }
    if (self.textView_reply.text.length > 0) {
        [param_dataArray addObject:@{@"type": @"TEXT" , @"text" : self.textView_reply.text}];
    }



    param_content = [param_dataArray JSONString];
    
    return isSuccess;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)btnClick_record:(id)sender {

}

- (IBAction)btnClick_camara:(id)sender {
    [self openCamera];
}

- (IBAction)btnClick_photo:(id)sender {
    [self openPhotoLib];
}

-(void)openCamera{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        picker.allowsEditing = YES;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

-(void)openPhotoLib{
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }
}


- (void)openEditor
{
    PECropViewController *controller = [[PECropViewController alloc] init];
    controller.delegate = self;
    controller.image = paramImage_process;

    UIImage *image = paramImage_process;
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    CGFloat length = MIN(width, height);
    controller.imageCropRect = CGRectMake((width - length) / 2,
                                          (height - length) / 2,
                                          length,
                                          length);

    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];

    [self presentViewController:navigationController animated:YES completion:nil];
}

#pragma mark - pickerImage Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

    UIImage *image = info[UIImagePickerControllerOriginalImage];
    paramImage_process = image;
    [picker dismissViewControllerAnimated:YES completion:^{
        [self openEditor];
    }];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -  PECropViewControllerDelegate
- (void)cropViewController:(PECropViewController *)controller didFinishCroppingImage:(UIImage *)croppedImage{

    NSMutableDictionary * param = [NSMutableDictionary dictionary];

    NSData * imageData = UIImageJPEGRepresentation(croppedImage, 0.1);
    NSString * imageString = [imageData base64EncodedStringWithOptions:0];

    [param setObject:imageString forKey:@"data"];
    [param setObject:@"jpg" forKey:@"extName"];

    [self showHUD:@""];

    [client uploadImage:param completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        if ([[object objectForKey:@"code"] integerValue] == 0) {
            if ([object objectForKey:@"data"]) {
                NSDictionary * tempDic = @{
                                           @"type": @"IMAGE",
                                           @"url": [object objectForKey:@"data"],
                                           };
                [param_dataArray addObject:tempDic];

                [self resetImageAndRecordViews];
            }
        }
        [self hideHUD];
    }];


    [controller dismissViewControllerAnimated:YES completion:nil];

}

- (void)cropViewControllerDidCancel:(PECropViewController *)controller{
    [controller dismissViewControllerAnimated:YES completion:nil];
}

-(void)resetImageAndRecordViews{

    for (UIView * tempView in self.contentOfImageView.subviews) {
        [tempView removeFromSuperview];
    }
    temp_scrollView_contentSize = hold_scrollView_contentSize;
    self.scrollView.contentSize = hold_scrollView_contentSize;

    float flag_height = 0;

    for (int i = 0; i < param_dataArray.count; i++) {
        NSDictionary * tempDic = param_dataArray[i];
        if ([tempDic[@"type"] isEqualToString:@"IMAGE"]) {
            UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10 + flag_height,CGRectGetWidth([[UIScreen mainScreen] bounds]) - 40, 190)];
            imageView.image = tempDic[@"url"]; //直接显示 再提交服务器
            //[imageView sd_setImageWithURL:[NSURL URLWithString:tempDic[@"url"]] placeholderImage:[UIImage imageNamed:@"首页-答疑-客观题-单选习题拍照图-通用"]];
            [self.contentOfImageView addSubview:imageView];
            flag_height += 200;

            if (temp_scrollView_contentSize.height < self.contentOfImageView.frame.origin.y + flag_height + 20) {
                temp_scrollView_contentSize = CGSizeMake(hold_scrollView_contentSize.width, hold_scrollView_contentSize.height + (self.contentOfImageView.frame.origin.y + flag_height + 20  - hold_scrollView_contentSize.height));
                self.scrollView.contentSize = temp_scrollView_contentSize;
            }
        }else if ([tempDic[@"type"] isEqualToString:@"VOICE"]){
            UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10 + flag_height, 120, 30)];
            UIImage * tempImage = [[UIImage imageNamed:@"bubble_stroked"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 30, 10, 30) resizingMode:UIImageResizingModeStretch];
            imageView.image = tempImage;

            UIImageView * imageRecord = [[UIImageView alloc]initWithFrame:CGRectMake(80, 5, 15, 20)];
            imageRecord.image = [UIImage imageNamed:@"horn_income_3"];
            [imageView addSubview:imageRecord];

            [self.contentOfImageView addSubview:imageView];
            flag_height += 40;

            if (temp_scrollView_contentSize.height < self.contentOfImageView.frame.origin.y + flag_height + 20) {

                temp_scrollView_contentSize = CGSizeMake(hold_scrollView_contentSize.width, hold_scrollView_contentSize.height + (self.contentOfImageView.frame.origin.y + flag_height + 20  - hold_scrollView_contentSize.height));


                self.scrollView.contentSize = temp_scrollView_contentSize;
            }

        }
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
